// pages/video/video.js

var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({

  /**
   * 页面的初始数据
   */

  data: {
    tabs: ["课程详情", "问答", "测验"],
    activeIndex: 1,
    sliderOffset: 0,
    sliderLeft: 0,
    isShowFrom1: false,
    isreply: false,
    thereply: false,
    quesid: "",
    defaulturl: '',

    // indicatorDots: true,
    // vertical: false,
    // autoplay: true,
    // interval: 3000,
    // duration: 800,
    // banner_url: banner.bannerList
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {

    var app = getApp()
    if (options != null) {
      console.log(options)
      if (options.lastlearnsectionid != null & options.classid != null & options.starttime != null) {
        // 设置继续学习的初始化信息
        console.log("开始0")

        this.getcontent(options);
        this.setData({
          starttime: options.starttime
        })
       
      } else {
        console.log("开始3")
        this.getcontent(options)
      }
    } else {
      this.getcontent(options)
    }
  },
  getcontent: function (options) {
    var app = getApp();
    if (app.globalData.openid == null) {
      this.getset()
    }
    console.log(options.classid)
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        console.log(that.data.tabs.length);
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });


    var testUrl = app.testUrl;
    wx.request({
      url: testUrl + '/lesson/findOne.do',
      data: {
        id: options.classid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var data = res.data
        var app = getApp()
        if (data.lessonQuestionList.length > 0) {
          for (var i = 0; i < data.lessonQuestionList.length; i++) {
            data.lessonQuestionList[i].createtime = app.dateto(data.lessonQuestionList[i].createtime)
          }
        }
        console.log(res.data)
        that.setData({
          autor: data.autor,
          detail: data.detail,
          classid: data.id,
          title: data.title,
          questionList: data.lessonQuestionList,
          sectionList: data.lessonSectionList,
        });
        console.log("开始设置默认地址")
        if (data.lessonSectionList.length > 0) {
          console.log("设置默认地址")
          that.setData({
            default_videourl: data.lessonSectionList[0].lessonSectionList[0].videoUrl,
            default_secordid: data.lessonSectionList[0].lessonSectionList[0].id
          })
        }
        console.log("课程" + that.data);
        if (options.lastlearnsectionid != null & options.classid != null & options.starttime != null) {
          console.log("开始1")
          that.tostudysection(options.lastlearnsectionid)
          console.log("开始2")

         
        }
      }
    });
  },
  // 获取设置信息
  getset: function () {

    var user = { info: {} }
    // 获取用户信息
    wx.getSetting({
      success: function (res) {
        console.log("获取设置信息成功")
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log("获取用户信息成功")
              // var that = getApp();
              console.log(res.userInfo)
              user.info.userinfo = res.userInfo
              // 登录
              wx.login({
                success: res => {
                  console.log(res)
                  // var that = getApp();
                  // that.code = res.code
                  user.code = res.code
                  var app = getApp()
                  var testurl = app.testUrl
                  wx.request({
                    url: testurl + '/user/getcode.do?code=',
                    data: {
                      code: res.code
                    },
                    header: {
                      'content-type': 'application/json' // 默认值
                    },
                    success: function (res) {
                      var app = getApp()
                      console.log(res)
                      user.info.openid = res.data.openid
                      user.info.userinfo.area = app.getc.getChina(user.info.userinfo.province) + " " + app.getc.getChina(user.info.userinfo.city),
                        console.log(user)
                      wx.setStorage({
                        key: "user",
                        data: user.info
                      })

                      // 设置用户信息
                      app.globalData.userInfo = user.info.userinfo
                      app.globalData.openid = user.info.openid
                      wx.request({
                        url: testurl + '/user/add.do',
                        method: "POST",
                        data: {
                          wxOpenid: user.info.openid,
                          wxUsername: user.info.userinfo.nickName,
                          userImg: user.info.userinfo.avatarUrl,
                          area: user.info.userinfo.area,
                          username: user.info.userinfo.nickName
                        },
                        header: {
                          'content-type': 'application/json' // 默认值
                        },
                        success: function (res) {
                          console.log(res)
                          var app = getApp()
                          console.log(app)
                        }
                      })

                    }
                  })
                  // 发送 res.code 到后台换取 openId, sessionKey, unionId
                },
                fail: function (res) {
                  console.log(res + "失败")
                }
              })


            },
            fail: function (e) {
              console.log(e + "获取用户信息失败")

            }
          })
        } else {
          console.log('没有获取授权')
          wx.redirectTo({
            url: '/pages/msg/msg_fail?page=1'
          })
        }
      },
      fail: function () {
        console.log("获取设置信息失败")
      }
    })


  },

  //   页签切换函数
  tabClick: function (e) {
    var that = this;
    console.log(e);
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
    // 获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        // 可使用窗口宽度、高度
        console.log('height=' + res.windowHeight);
        console.log('width=' + res.windowWidth);
        // 计算主体部分高度,单位为px
        that.setData({
          // second部分高度 = 利用窗口可使用高度 - first部分高度（这里的高度单位为px，所有利用比例将300rpx转换为px）
          second_height: res.windowHeight - res.windowWidth / 750 * 300
        })
      }
    })
    if (e.currentTarget.id == 2) {
      console.log(e.currentTarget);
      wx.navigateTo({
        url: '/pages/test/test',
      })
    }

  },

  slectsection: function (e) {
    console.log('12323123123112312123');
    var that = this
    var sectionid = e.target.dataset.sectionid
    var sectionList = that.data.sectionList
    console.log(e)
    for (var i = 0; i < sectionList.length; i++) {
      for (var k = 0; k <= sectionList[i].lessonSectionList.length - 1; k++) {
        // console.log(sectionList[i].lessonSectionList[k])
        if (sectionList[i].lessonSectionList[k].hasOwnProperty('id')) {
          var videoid = sectionList[i].lessonSectionList[k].id
          // console.log(videoid)
          if (sectionid == videoid) {
            that.setData({
              defaulturl: sectionList[i].lessonSectionList[k].videoUrl,
              default_secordid: videoid,
              starttime:0
            })
          }

        }

      }
    }
  },


  tostudysection: function (id) {
    console.log("运行到设置函数")
    var that = this
    var sectionid = id
    // console.log(that.data) 
    var sectionList = that.data.sectionList;
    console.log('sectionList',sectionList)
    for (var i = 0; i < sectionList.length; i++) {
      for (var k = 0; k <= sectionList[i].lessonSectionList.length - 1; k++) {
        console.log(sectionList[i].lessonSectionList[k])
        if (sectionList[i].lessonSectionList[k].hasOwnProperty('id')) {

          var videoid = sectionList[i].lessonSectionList[k].id
          // console.log(sectionid,videoid)
          if (sectionid == videoid) {
            console.log('sectionList[i].lessonSectionList[k].videoUrl})',sectionList[i].lessonSectionList[k].videoUrl)
            that.setData({
              defaulturl: sectionList[i].lessonSectionList[k].videoUrl
            })
          }
        }
      }
    }
  },

  videorecord: function (e) {
    var n1 = Math.floor(Math.random() * 100 + 1);
    // console.log(n1)
    if (n1 < 90) return

    var that = this
    var app = getApp()
    var testurl = app.testUrl
    var index = 0;
    var sumsection = 0;
    var flat = false
    console.log(e)
    for (var i = 0; i < that.data.sectionList.length; i++) {
      var section = that.data.sectionList[i].lessonSectionList
      console.log(section)
      sumsection = sumsection + section.length
      console.log(sumsection)
      for (var j = 0; j < section.length; j++) {
        if (flat == true) break;
        index = index + 1;
        if (that.data.default_secordid == section[j].id) {
          flat = true
          break
        }
      }

    }
    console.log(index + " " + sumsection)
    var percent = parseInt((index / sumsection) * 100)
    console.log(percent)
    wx.request({
      url: testurl + "/lessonRecord/add.do",
      method: "POST",
      data: {
        lastLearnSectionId: that.data.default_secordid,
        jinduPer: percent,
        userId: app.globalData.openid,
        startTime: e.detail.currentTime,
        lessonId: that.data.classid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data)
      }
    })

  },

  // 发表问题的接口
  comment: function () {
    var app = getApp();
    var testUrl = app.testUrl;
    var that = this;
    wx.request({
      url: testUrl + '/lessonQuestion/add.do',
      method: "post",
      data: {
        "lessonId": that.data.classid,
        "userId": app.globalData.openid,
        "content": that.data.commentContent,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        if (res.data.success == true) {
          console.log("代开")
          that.openToast();
          var app = getApp();
          var testUrl = app.testUrl;
          wx.request({
            url: testUrl + '/lesson/findOne.do',
            data: {
              id: that.data.classid
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              console.log(res.data)
              var data = res.data


              var app = getApp()
              if (data.lessonQuestionList.length > 0) {
                for (var i = 0; i < data.lessonQuestionList.length; i++) {
                  data.lessonQuestionList[i].createtime = app.dateto(data.lessonQuestionList[i].createtime)
                }
              }
              console.log(that)
              that.setData({
                questionList: data.lessonQuestionList,
              });

            }
          });
        }
      }
    });
  },
  //   输入框绑定函数
  inputComment: function (e) {
    var that = this;
    console.log(e)
    that.setData({
      commentContent: e.detail.value
    });
  },



  // theinputComment: function (e) {
  //   var that = this;
  //   console.log(e)
  //   that.setData({
  //     // isreply: false,
  //     thereply: true,
  //   });
  // },




  openToast: function () {
    wx.showToast({
      title: '提问成功',
      icon: 'success',
      duration: 3000
    });
  },

  openToast2: function () {
    wx.showToast({
      title: '回复成功',
      icon: 'success',
      duration: 3000
    });
  },

  reply: function (e) {
    var that = this;
    console.log(e)
    that.setData({
      isreply: true,
      // thereply: false,
      quesid: e.currentTarget.dataset.quesid
    });
  },

  replycontent: function (e) {
    var that = this;
    console.log(e)
    that.setData({
      replycontent: e.detail.value
    });
  },
  toreply: function () {
    var app = getApp();
    var testUrl = app.testUrl;
    var that = this;
    wx.request({
      url: testUrl + '/lessonReply/add.do',
      method: "post",
      data: {
        "lessonId": that.data.classid,
        "userId": app.globalData.openid,
        "content": that.data.replycontent,
        "lessonQuestionId": that.data.quesid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        if (res.data.success == true) {
          console.log("代开")
          that.openToast2();
          var app = getApp();
          var testUrl = app.testUrl;

          wx.request({
            url: testUrl + '/lesson/findOne.do',
            data: {
              id: that.data.classid
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              console.log(res.data)
              var data = res.data


              var app = getApp()
              if (data.lessonQuestionList.length > 0) {
                for (var i = 0; i < data.lessonQuestionList.length; i++) {
                  data.lessonQuestionList[i].createtime = app.dateto(data.lessonQuestionList[i].createtime)
                }
              }
              console.log(that)
              that.setData({
                questionList: data.lessonQuestionList,
              });
            }
          });
        }
      }
    });
    console.log(e)
  },
  tiwen: function () {
    var that = this;

    that.setData({
      isreply: false
    });
  },

  showinfo: function () {
    var app = this
    console.log(app.currentTarget)


  },
  // showFrom:function(e) {
  //   var param = e.target.dataset.param;
  //   this.setData({
  //     isShowFrom1: param == 1 ? (this.data.isShowFrom1 ? false : true) : false,
  //     isShowFrom2: param == 2 ? (this.data.isShowFrom2 ? false : true) : false,
  //     isShowFrom3: param == 3 ? (this.data.isShowFrom3 ? false : true) : false
  //   });
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  myfun: function () {
    console.log("hello")
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})